package com.bwie.auto.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.bwie.auto.feign.FeignWeiboLogin;
import com.bwie.common.utils.HttpUtils;
import com.bwie.common.utils.R;
import com.bwie.common.vo.UserdVo;
import com.bwie.common.vo.WeiboAccessVo;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;

/**
 * @author 龙
 * @version 1.0.0
 * @ClassName WebController.java
 * @Description TODO
 * @createTime 2022年04月28日 12:27:00
 */
@Controller
public class WebController {

    @Autowired
    private FeignWeiboLogin feignWeiboLogin;

    //微博登录
    @GetMapping("/oauth2.0/weibo/success")
    public String weiboSuccess(@RequestParam("code") String code, HttpSession session, Model model) throws Exception {
        //提前
        HashMap<String, String> map = new HashMap<>();
        map.put("client_id","2212446455");
        map.put("client_secret","53a19740364d5f8864bb7f690409a313");
        map.put("grant_type","authorization_code");
        map.put("redirect_uri", "http://localhost:88/api/oauth2.0/weibo/success");
        map.put("code",code);
        HttpResponse httpResponse = HttpUtils.doPost("https://api.weibo.com/oauth2/access_token", "", "post", null, map, "");
        String s = EntityUtils.toString(httpResponse.getEntity());
        WeiboAccessVo weiboAccessVo = JSON.parseObject(s, new TypeReference<WeiboAccessVo>() {
        });
        System.out.println("session"+session);
        System.out.println("=="+weiboAccessVo);
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        System.out.println("code:"+statusCode);
        //通过feign调用完成登录注册
        if (statusCode==200){
            R r = feignWeiboLogin.weiboLogin(weiboAccessVo);
            if (r.getCode()==0){
//                UserdVo userdVo = r.getData(new org.apache.ibatis.type.TypeReference<UserdVo>() {
//                });
//                session.setAttribute("user",userdVo);
                System.out.println("登录成功");
                //
                return "redirect:http://127.0.0.1:5500/home.html";
            }
        }
        model.addAttribute("error","登录失败");
        return "登录失败";
    }
}
